package com.xiaoye.qbproject.controller.qbzyk;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaoye.qbproject.config.XiaoYeConfig;
import com.xiaoye.qbproject.controller.base.BaseController;
import com.xiaoye.qbproject.domain.AjaxResult;
import com.xiaoye.qbproject.domain.QbWarfare;
import com.xiaoye.qbproject.domain.QbWarfareExamples;
import com.xiaoye.qbproject.domain.QbWarfareMedia;
import com.xiaoye.qbproject.page.TableDataInfo;
import com.xiaoye.qbproject.service.QbWarfareExamplesService;
import com.xiaoye.qbproject.service.QbWarfareMediaService;
import com.xiaoye.qbproject.service.QbWarfareService;
import com.xiaoye.qbproject.util.StringUtils;
import com.xiaoye.qbproject.util.poi.ExcelUtil;
import com.xiaoye.qbproject.util.poi.WarfareExamplesV2ExcelUtil;
import com.xiaoye.qbproject.util.uuid.UUID;
import com.xiaoye.qbproject.vo.QbWarfareExamplesImportV2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : ChenYao
 * @version : 1.0
 * @description : 战争战例
 * @create : 2024-12-30 14:42
 */
@Slf4j
@RestController
@RequestMapping("/warfareExamples")
public class QbWarfareExamplesController extends BaseController {
    @Autowired
    private QbWarfareExamplesService qbWarfareExamplesService;
    @Autowired
    private QbWarfareService qbWarfareService;
    @Autowired
    private QbWarfareMediaService qbWarfareMediaService;

    @GetMapping("/list")
    public TableDataInfo list(QbWarfareExamples qbWarfareExamples) {
        startPage();
        LambdaQueryWrapper<QbWarfareExamples> queryWrapper = Wrappers.lambdaQuery();

        String name = qbWarfareExamples.getName();
        String title = qbWarfareExamples.getTitle();
        String classifyLabel = qbWarfareExamples.getClassifyLabel();
        String equipLabel = qbWarfareExamples.getEquipLabel();
        String warfareId = qbWarfareExamples.getWarfareId();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(QbWarfareExamples::getName, name);
        }
        if (StringUtils.isNotBlank(title)) {
            queryWrapper.like(QbWarfareExamples::getTitle, title);
        }
        if (StringUtils.isNotBlank(classifyLabel)) {
            queryWrapper.like(QbWarfareExamples::getClassifyLabel, classifyLabel);
        }
        if (StringUtils.isNotBlank(equipLabel)) {
            queryWrapper.like(QbWarfareExamples::getEquipLabel, equipLabel);
        }
        if (StringUtils.isNotBlank(warfareId)) {
            queryWrapper.eq(QbWarfareExamples::getWarfareId, warfareId);
        }
        List<QbWarfareExamples> list = qbWarfareExamplesService.list(queryWrapper
                .select(QbWarfareExamples::getId, QbWarfareExamples::getName, QbWarfareExamples::getTitle
                        , QbWarfareExamples::getWarfareId,QbWarfareExamples::getFightTime,QbWarfareExamples::getFightAddress
                ,QbWarfareExamples::getAggressor,QbWarfareExamples::getDefense)
                .orderByDesc(QbWarfareExamples::getFightTime)
        );
        // 查询战争名称
        if (CollectionUtils.isNotEmpty(list)) {
            LambdaQueryWrapper<QbWarfare> wrapper = Wrappers.<QbWarfare>lambdaQuery().select(QbWarfare::getId, QbWarfare::getName);
            if (StringUtils.isNotBlank(warfareId)){
                wrapper.eq(QbWarfare::getId,warfareId);
            }
            List<QbWarfare> qbWarfareList = qbWarfareService.list(wrapper);
            Map<String, String> map = qbWarfareList.stream().collect(Collectors.toMap(QbWarfare::getId, QbWarfare::getName));
            list.forEach(item -> item.setWarfareName(map.get(item.getWarfareId())));
        }
        return getDataTable(list);
    }

    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable String id) {
        QbWarfareExamples examples = qbWarfareExamplesService.getById(id);
        if (examples != null) {
            // 查询关联的多媒体数据
            List<QbWarfareMedia> mediaList = qbWarfareMediaService.listByWarfareId(examples.getId());
            examples.setMediaList(mediaList);
            return success(examples);
        }
        return error("未找到相关战例信息");
    }

    /***
     * @description: 获取 战例下拉数据
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.AjaxResult
     * @ceateDate: 2025-01-02 13:15
     */

    @GetMapping("dropDown")
    public AjaxResult dropDown() {
        return success(qbWarfareExamplesService.dropDown());
    }

    @PostMapping
    public AjaxResult save(@RequestBody QbWarfareExamples qbWarfareExamples) {
        return toAjax(qbWarfareExamplesService.saveOrUpdate(qbWarfareExamples));
    }

    @PutMapping
    public AjaxResult update(@RequestBody QbWarfareExamples qbWarfareExamples) {
        return toAjax(qbWarfareExamplesService.updateById(qbWarfareExamples));
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable String id) {
        return toAjax(qbWarfareExamplesService.removeById(id));
    }

    /**
     * @param file
     * @description: 导入
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.AjaxResult
     * @ceateDate: 2024-12-30 16:19
     */

    @PostMapping(value = "import", consumes = "multipart/form-data")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        ExcelUtil<QbWarfareExamples> util = new ExcelUtil<QbWarfareExamples>(QbWarfareExamples.class);
        List<QbWarfareExamples> qbWarfareExamples = util.importExcel(file.getInputStream());
        qbWarfareExamplesService.importExcel(qbWarfareExamples);
        return AjaxResult.success("正在导入...请稍后");
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<QbWarfareExamples> util = new ExcelUtil<QbWarfareExamples>(QbWarfareExamples.class);
        util.importTemplateExcel(response, "战例数据模版文件");
    }

    @PostMapping(value = "/exportOwl", produces = MediaType.TEXT_XML_VALUE)
    public void exportOwl(@RequestBody String[] ids, HttpServletResponse response) {
        // 设置响应头信息
        response.setHeader("Content-Disposition", "attachment; filename=\"QB_WARFARE_EXAMPLES_" + UUID.fastUUID() + ".owl\"");
        response.setHeader("Content-Type", "application/xml;charset=UTF-8");
        log.info("开始导出战例数据...:{}", ids);
        // 调用服务方法导出数据
        qbWarfareExamplesService.exportOwl(ids, response);
    }

    @PostMapping("importWarfareExamplesInfoV2")
    public AjaxResult importWarfareExamplesInfoV2(@RequestParam("file") MultipartFile file) {
        // 获取文件名
        String filename = file.getOriginalFilename();
        File file1 = new File(XiaoYeConfig.getImportPath() + File.separator + filename);
        file1.getParentFile().mkdirs();
        try {
            file.transferTo(file1);
            // 请求中获取上传的文件
            WarfareExamplesV2ExcelUtil excelUtil = new WarfareExamplesV2ExcelUtil();
            Map<String, Object> muchSheetToObj = excelUtil.readExcelMuchSheetToObj(file1.getPath());
            muchSheetToObj.forEach((key, value) -> {
                List<QbWarfareExamplesImportV2Vo> qbWarfareExamplesImportV2Vos = (List<QbWarfareExamplesImportV2Vo>) value;
                qbWarfareExamplesService.saveWarfareExamlesV2(qbWarfareExamplesImportV2Vos, key);
            });
            return success("导入成功");

        } catch (IOException e) {
            e.getLocalizedMessage();
            log.error("导入失败", e.getLocalizedMessage());
            return AjaxResult.error("上传失败");
        }
    }
}
